/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ctrl;

import entities.GuestUser;
import hotel.jpa.Database;
import java.io.IOException;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.el.ELContext;
import javax.el.ExpressionFactory;
import javax.el.ValueExpression;
import javax.faces.application.Application;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.ExternalContext;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import model.LoginBackingBean;

/**
 *
 * @author Anton
 */
@ManagedBean(name = "loginBean")
@SessionScoped
public class LoginBean {

    /**
     * A user can login. Looks so the user has correct password. 
     * @return String UrlPath
     */
    public String login() {
        
        //Using other bean (LoginBackingBean)
        FacesContext ctx = FacesContext.getCurrentInstance();
        Application app = ctx.getApplication();
        ELContext ectx = ctx.getELContext();
        ExpressionFactory ef = app.getExpressionFactory();
        ValueExpression ve = ef.createValueExpression(ectx, "#{loginBackingBean}", LoginBackingBean.class);
        LoginBackingBean db = (LoginBackingBean) ve.getValue(ectx);
        
        List<GuestUser> users = Database.getUserController().findEntities();

        GuestUser aUser = null;
        for (GuestUser u : users) {
            if (u.getName().compareTo(db.getUsername()) == 0 && u.getPwd().compareTo(db.getPassword()) == 0) {
                aUser = u;
            }
        }

        if (aUser != null) {
         
            HttpServletRequest req = (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
            HttpSession session = req.getSession();

            session.setAttribute("loginUser", aUser);

         
            return "user/mypage.xhtml";

        } else {
                
            try {
                FacesContext.getCurrentInstance().getExternalContext().redirect("login.jsf?error=1");
            } catch (IOException ex) {
                Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
            }
            return "";
        }
    }

    /**
     * Invalidates the current session. 
     * And the user will be logged out and redirected to the welcomepage 
     * @return String UrlPath
     */
    public String logout() {
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext ec = context.getExternalContext();

        final HttpServletRequest request = (HttpServletRequest) ec.getRequest();
        request.getSession(false).invalidate();

        return "../welcome.xhtml";
    }

    /**
     * Redirect to login.jsf if not logged in user is trying to access a restricted page.
     * 
     * @return 
     */
    public String getIsLogin() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);

        if (session.getAttribute("loginUser") == null) {
            try {
                context.getExternalContext().redirect("/hotel-1.0-SNAPSHOT/login.jsf?loginfirst=1");
            } catch (IOException ex) {
                Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return "";
    }

    /**
     * Redirect to login.jsf if not admin user is trying to access admin page.
     * 
     * @return 
     */
    public String getIsAdminLogin() {
        FacesContext context = FacesContext.getCurrentInstance();
        HttpSession session = (HttpSession) context.getExternalContext().getSession(false);
        GuestUser sessionUser = (GuestUser) session.getAttribute("loginUser");

        if (sessionUser == null || sessionUser.getAuth() == 0) {
            try {
                context.getExternalContext().redirect("../login.jsf?adminonly=1");
            } catch (IOException ex) {
                Logger.getLogger(LoginBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        }

        return "";
    }
}
